//
//  EmoticonView.swift
//  01-keyBoard
//
//  Created by Leon on 15/10/23.
//  Copyright © 2015年 Leon. All rights reserved.
//

import UIKit

/// 表情可重用ID
private let emoticonCollectionID = "emoticonCollectionID"

// MARK: - 表情键盘视图
class EmoticonView: UIView {
    
    /// 点击传递闭包
    private var clickItemCallBack:(emoticon: EmoticonModel) -> ()
    
    /// 表情包模型
    lazy var packages = EmoticonManager.shareManager.packages
    
    ///  toolBar点击事件
    ///
    ///  - parameter item: 点击的 item
    @objc private func clickEmoticonToolBar(item: UIBarButtonItem) {
        
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        
        emoticonCollection.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }

    // MARK: - 构造函数
    init (clickItem:(emoticon: EmoticonModel) -> ()) {
        
        clickItemCallBack = clickItem
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = rect.height * 0.32
        
        super.init(frame: rect)
        backgroundColor = UIColor.whiteColor()
        
        // 设置界面
        setupUI()
        
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            // 滚动到第一页
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            self.emoticonCollection.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)

        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MRKE: - 懒加载
    private lazy var emoticonCollection = UICollectionView(frame: CGRectZero, collectionViewLayout:EmoticonViewLayout())
    private lazy var emoticonToolBar = UIToolbar()
    
    /// 表情键盘视图布局
    private class EmoticonViewLayout: UICollectionViewFlowLayout {
 
        override func prepareLayout() {
            super.prepareLayout()
            
            let row: CGFloat = 3
            let col: CGFloat = 7
            
            // 取消间隔
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            
            let w = UIScreen.mainScreen().bounds.width / col
            
            //设置 item 的大小
            itemSize = CGSizeMake(w, w)
            
            // 增加上下边距
            let margin = (collectionView!.bounds.height - w * row) / 2
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            
            // 设置滑动方向
            scrollDirection = .Horizontal
            
            // 取消弹簧效果 & 分页
            collectionView?.bounces = false
            collectionView?.pagingEnabled = true
            
            // 隐藏滑动条
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
}

// MARK: - 设置界面
private extension EmoticonView {

    ///  界面布局
    func setupUI() {
        // 1 添加控件
        addSubview(emoticonToolBar)
        addSubview(emoticonCollection)
        
        // 2 自动布局
        emoticonCollection.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(emoticonToolBar.snp_top)
        }
        
        emoticonToolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left)
            make.width.equalTo(self.snp_width)
            make.bottom.equalTo(self.snp_bottom)
        }
        
        // 3 准备控件内部
        prepareEmoticonToolBar()
        prepareEmoticonCollection()
    }
    
    ///  准备工具栏
    func prepareEmoticonToolBar() {
        emoticonToolBar.tintColor = UIColor.orangeColor()
        
        var items = [UIBarButtonItem]()
        var index = 0
        
        for p in packages {
            
            items.append(UIBarButtonItem(title: p.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "clickEmoticonToolBar:"))
            
            items.last?.tag = index++
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        emoticonToolBar.items = items
    }
    
    ///  准备
    func prepareEmoticonCollection() {
        emoticonCollection.backgroundColor = UIColor.lightGrayColor()
        
        // 注册cell
        emoticonCollection.registerClass(EmoticonCollectionCell.self, forCellWithReuseIdentifier: emoticonCollectionID)
        // 设置数据源
        emoticonCollection.dataSource = self
        emoticonCollection.delegate = self
    }
}

// MARK: - UICollectionViewDataSource
extension EmoticonView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    // 点击item
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 利用闭包传递 点击的表情
        let emoticon = packages[indexPath.section].emoticons[indexPath.row]
        clickItemCallBack(emoticon: emoticon)
        
        // 添加最近使用的表情
        if indexPath.section > 0 {
            
            EmoticonManager.shareManager.addFavorite(emoticon)
        }
        
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emoticonCollectionID, forIndexPath: indexPath) as! EmoticonCollectionCell
        
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.row]
        
        return cell
    }
}

// MARK: - 自定义cell
private class EmoticonCollectionCell: UICollectionViewCell {
    
    /// 表情模型
    var emoticon:EmoticonModel? {
        didSet {
            emoticonButton.setTitle(emoticon?.code, forState: .Normal)
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: .Normal)
            
            if emoticon!.isRemoved {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
            }
        }
    }
    
    // MARK: - 构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(emoticonButton)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.frame = CGRectInset(self.bounds, 4, 4)
        // 利用 collectionCell 的点击，所以取消按钮的交互
        emoticonButton.userInteractionEnabled = false
        // emoji 其实是字符编码 想变大，就放大字号
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(36)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
     // MARK: -  懒加载
    private lazy var emoticonButton = UIButton()
}






